package com.smarttable.ysd;

import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.smarttable.ysd.manager.SharedPreferenceManager;
import com.umeng.analytics.MobclickAgent;


public class UnlockGesturePasswordActivity extends Activity {
	private LockPatternView mLockPatternView;
	private int mFailedPatternAttemptsSinceLastTimeout = 0;
	private CountDownTimer mCountdownTimer = null;
	private Handler mHandler = new Handler();
	private TextView mHeadTextView;
	private Animation mShakeAnim;
	private Toast mToast;
	private static boolean mWaitingTimeout;
	private static int mTimeRemaining;
	private ViewGroup mRoot;
	private String mUnlockType;

	private void showToast(CharSequence message) {
		if (null == mToast) {
			mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
			mToast.setGravity(Gravity.CENTER, 0, 0);
		} else {
			mToast.setText(message);
		}

		mToast.show();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gesturepassword_unlock);
		mUnlockType = getIntent().getStringExtra("unlock_type");
		mRoot = (ViewGroup)this.findViewById(R.id.gesturepwd_root);
		mLockPatternView = (LockPatternView) this
				.findViewById(R.id.gesturepwd_unlock_lockview);
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		mLockPatternView.setTactileFeedbackEnabled(true);
		mHeadTextView = (TextView) findViewById(R.id.gesturepwd_unlock_text);
		mShakeAnim = AnimationUtils.loadAnimation(this, R.anim.shake_x);
		mHeadTextView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new HideClick().start();
				if (HideClick.sIsAlive >= 10) {
					Toast.makeText(UnlockGesturePasswordActivity.this, "芝麻开门", Toast.LENGTH_SHORT).show();
					Intent intent = new Intent();
					intent.setClass(UnlockGesturePasswordActivity.this, CreateGesturePasswordActivity.class);
					UnlockGesturePasswordActivity.this.startActivity(intent);
				}
			}
		});
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
//		if (!App.getInstance().getLockPatternUtils().savedPatternExists()) {
//			startActivity(new Intent(this, GuideGesturePasswordActivity.class));
//			finish();
//		}
		if(!mWaitingTimeout && mTimeRemaining > 0){
			mLockPatternView.setEnabled(false);
			mCountdownTimer = new CountDownTimer(
					mTimeRemaining * 1000 + 1, 1000) {

				@Override
				public void onTick(long millisUntilFinished) {
					int secondsRemaining = (int) (millisUntilFinished / 1000) - 1;
					mTimeRemaining = secondsRemaining;
					if (secondsRemaining > 0) {
						mHeadTextView.setText(secondsRemaining + " 秒后重试");
						mWaitingTimeout = false;
					} else {
						mHeadTextView.setText("请绘制手势密码");
						mHeadTextView.setTextColor(Color.WHITE);
					}
				}

				@Override
				public void onFinish() {
					mLockPatternView.setEnabled(true);
					mFailedPatternAttemptsSinceLastTimeout = 0;
					mWaitingTimeout = true;
				}
			}.start();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mCountdownTimer != null)
			mCountdownTimer.cancel();
	}
	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			mLockPatternView.clearPattern();
		}
	};

	protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {

		public void onPatternStart() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}

		@Override
		public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {

		}

		public void onPatternDetected(List<LockPatternView.Cell> pattern) {
			if (pattern == null)
				return;
			if (!App.getInstance().getLockPatternUtils().savedPatternExists())
			{
				if(App.getInstance().getLockPatternUtils().checkDefaultPassword(pattern))
				{
					unlockSuccess();
				}
				else
				{
					unlockError(pattern);
				}
				return;
			}
			if (App.getInstance().getLockPatternUtils().checkPattern(pattern)) {
				unlockSuccess();
			} else {
				unlockError(pattern);
			}
		}

		private void patternInProgress() {
		}
	};

	private void unlockSuccess() {
		mLockPatternView
				.setDisplayMode(LockPatternView.DisplayMode.Correct);
		if (mUnlockType != null)
		{
			showToast("解锁成功");
			SharedPreferenceManager.getInstance(this).saveGestureUnLock(true);
			finish();
			return;
		}
		try {
            Intent intent = new Intent();
//            ComponentName componentName = new ComponentName("com.android.launcher3","com.android.launcher3.Launcher");
//            intent.setComponent(componentName);
			intent.setClass(this,AdminSettingActivity.class);
			startActivity(intent);
            showToast("解锁成功");
            finish();
        }catch (Exception e){

        }
	}

	private void unlockError(List<LockPatternView.Cell> pattern)
	{
			mLockPatternView
					.setDisplayMode(LockPatternView.DisplayMode.Wrong);
			if (pattern.size() >= LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
				mFailedPatternAttemptsSinceLastTimeout++;
				int retry = LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT
						- mFailedPatternAttemptsSinceLastTimeout;
				if (retry >= 0) {
					if (retry == 0)
						showToast("您已3次输错密码，请30秒后再试");
					mHeadTextView.setText("密码错误，还可以再输入" + retry + "次");
					mHeadTextView.setTextColor(Color.RED);
					mHeadTextView.startAnimation(mShakeAnim);
				}

			}else{
				showToast("输入长度不够，请重试");
			}

			if (mFailedPatternAttemptsSinceLastTimeout >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
				mHandler.postDelayed(attemptLockout, 2000);
			} else {
				mLockPatternView.postDelayed(mClearPatternRunnable, 2000);
			}
	}

	Runnable attemptLockout = new Runnable() {

		@Override
		public void run() {
			mLockPatternView.clearPattern();
			mLockPatternView.setEnabled(false);
			mCountdownTimer = new CountDownTimer(
					LockPatternUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1, 1000) {

				@Override
				public void onTick(long millisUntilFinished) {
					int secondsRemaining = (int) (millisUntilFinished / 1000) - 1;
					mTimeRemaining = secondsRemaining;
					if (secondsRemaining > 0) {
						mHeadTextView.setText(secondsRemaining + " 秒后重试");
						mWaitingTimeout = false;
					} else {
						mHeadTextView.setText("请绘制手势密码");
						mHeadTextView.setTextColor(Color.WHITE);
					}

				}

				@Override
				public void onFinish() {
					mLockPatternView.setEnabled(true);
					mFailedPatternAttemptsSinceLastTimeout = 0;
					mWaitingTimeout = true;
				}
			}.start();
		}
	};

	static class HideClick extends Thread {
		public static volatile int sIsAlive = 0;
		@Override
		public void run() {
			sIsAlive++;
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (sIsAlive > 0) {
				sIsAlive--;
			}
			super.run();

		}
	}

	@Override
	public void finish() {
		super.finish();
		if (mUnlockType != null)
		{
			this.overridePendingTransition(0, R.anim.push_bottom_out);
		}
	}

}
